from flask import jsonify
from flask_login import login_required, \
    current_user
from sqlalchemy import asc
from ..base import base
from ..models import Resource, ResourceType


def setAccessable(resource, permitedIDList):
    if resource.ID not in permitedIDList:
        resource.HIDDEN = True
    
    for child in resource.children:
        setAccessable(child, permitedIDList)

@base.route('/getRouters')
@login_required
def getRouters():
    resources = []
    resources += [res for org in current_user.organizations for res in org.resources if org.resources]
    resources += [res for role in current_user.roles for res in role.resources if role.resources]
    
    ids = [res.ID for res in resources]
    
    allResources = Resource.query.join(ResourceType, Resource.type).filter(
        Resource.SYRESOURCE_ID == None).order_by(asc(getattr(Resource, 'SEQ'))).all()

    for res in allResources:
       setAccessable(res, ids)

    json = [res.to_router_json() for res in allResources]

    return jsonify({'msg': '操作成功', 'code': 200, "data": json})    
